//
//  PreviewImageCollectionViewCell.swift
//  SNVIPER
//
//  Created by shaofeng on 2017/5/19.
//  Copyright © 2017年 shaofeng. All rights reserved.
//

import UIKit
import Kingfisher

class SNPreviewImageCollectionViewCell: UICollectionViewCell {
    
    var previewView: SNPreviewImageView?;
    var singleTapGestureBlock: SingleTapGestureBlock?;
    
    var _urlStr: String = "";
    
    var urlStr: String {
        get {
            return _urlStr;
        }
        set {
            _urlStr = newValue;
            let url = URL(string: newValue);
            previewView?.imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { [weak self](image, error, cacheType, url) in
                self?.previewView?.imageView.image = image;
            });
        }
    }
    
    var _allowCrop: Bool = false;
    
    var allowCrop: Bool {
        get {
            return _allowCrop;
        }
        
        set {
            _allowCrop = newValue;
            previewView?.allowCrop = newValue;
        }
    }
    
    var _cropRect: CGRect = .zero;
    
    var cropRect: CGRect {
        get {
            return _cropRect;
        }
        
        set {
            _cropRect = newValue;
            previewView?.cropRect = newValue;
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        
        previewView = SNPreviewImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height));
        self.contentView.addSubview(previewView!);
        previewView?.singleTapGestureBlock = { [weak self] in
            self?.singleTapGestureBlock?();
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func recoverSubviews() {
        previewView?.recoverSubviews();
    }
    
    func setData(data: Any) {
        
        if let urlStr: String = data as? String {
            previewView?.setImageUrl(url: urlStr)
        }
        else if let image = data as? UIImage {
            previewView?.imageView.image = image;
        }
        else {
            previewView?.imageView.image = nil;
        }
    }
}
